/**
 * Created by feifan on 2016/6/4.
 */
var express = require('express');

var router = express.Router();
var token = require('../lib/token')(20);

router.get('/', function (req, res) {
    var t = token();
    req.session.token = t;
    res.send('<div id="admin" class="row center row-center">' +
        '<div class="col col-8">' +
        '<form class="form" target="_blank" method="post" action="/login">' +
        '<div class="form-group row">' +
        '<span class="col-sm-3">username:</span><div class="col-sm-9"><input type="text" name="username" placeholder="username"></div></div>' +
        '<div class="form-group row"><span class="col-sm-3">password:</span><div class="col-sm-9"><input type="password" name="password" placeholder="password">' +
        '<input type="hidden" name="token" value="' + t + '"></div></div>' +
        '<div class="form-group row center"><div class="col"><button type="submit" class="btn">submit</button></div></div>' +
        '</form></div></div>');
});

router.post('/', function (req, res) {
    //db.findOne('user', {user: "123",pwd:'321'}, (data)=> {
    db.findOne('user', {user: req.body.username, pwd: req.body.password}, (data)=> {
        //log(req.body.user,req.body.pwd);
        if (req.session.token != req.body.token) {
            res.json({status: 0, info: 'error'});
        } else if (!data) {
            res.json({status: 0, info: 'user does not exist!'});
        } else {
            req.session.auth = 1;
            res.redirect('/editor');
            //res.json({status: 1})
        }
    });
});

module.exports = router;